import React, { useState, useEffect } from 'react';
import { getNodes, createNode, updateNode, deleteNode } from '../../api/cdnNodeApi';
import { CdnNode } from '../../types/CdnNode';


const CdnNodePage = () => {
  const [nodes, setNodes] = useState<CdnNode[]>([]);
  const [showModal, setShowModal] = useState(false);
  const [currentNode, setCurrentNode] = useState<Partial<CdnNode> | null>(null);

  const fetchNodes = async () => {
    try {
      const res = await getNodes();
      setNodes(res);
    } catch (error) {
      console.error(error);
    }
  };

  useEffect(() => {
    fetchNodes();
  }, []);

  const handleEdit = (node: CdnNode) => {
    setCurrentNode(node);
    setShowModal(true);
  };

  const handleDelete = async (id: number) => {
    if (window.confirm('确定要删除该节点吗？')) {
      await deleteNode(id);
      fetchNodes();
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (currentNode?.id) {
      await updateNode(currentNode.id, currentNode);
    } else {
      await createNode(currentNode);
    }
    setShowModal(false);
    setCurrentNode(null);
    fetchNodes();
  };

  return (
    <div className="p-6 bg-gray-50 dark:bg-gray-900 min-h-screen">
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-3xl font-bold text-gray-900 dark:text-white">CDN 节点管理</h1>
        <button
          className="bg-blue-600 text-white py-2 px-5 rounded-lg hover:bg-blue-700"
          onClick={() => { setCurrentNode({}); setShowModal(true); }}
        >
          + 新增节点
        </button>
      </div>

      <div className="overflow-x-auto rounded-lg shadow">
        <table className="w-full text-sm text-left text-gray-600 dark:text-gray-300">
          <thead className="text-xs uppercase bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300">
            <tr>
              <th className="px-6 py-3">ID</th>
              <th className="px-6 py-3">节点名称</th>
              <th className="px-6 py-3">Host</th>
              <th className="px-6 py-3">SSH 用户</th>
              <th className="px-6 py-3">SSH 端口</th>
              <th className="px-6 py-3">状态</th>
              <th className="px-6 py-3 text-right">操作</th>
            </tr>
          </thead>
          <tbody>
            {nodes.map(node => (
              <tr key={node.id} className="bg-white border-b dark:bg-gray-800 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-600">
                <td className="px-6 py-4">{node.id}</td>
                <td className="px-6 py-4">{node.name}</td>
                <td className="px-6 py-4">{node.host}</td>
                <td className="px-6 py-4">{node.ssh_user}</td>
                <td className="px-6 py-4">{node.ssh_port}</td>
                <td className="px-6 py-4">{node.status ? '启用' : '禁用'}</td>
                <td className="px-6 py-4 flex justify-end space-x-2">
                  <button
                    className="bg-blue-500 text-white py-1.5 px-3 rounded hover:bg-blue-600"
                    onClick={() => handleEdit(node)}
                  >编辑</button>
                  <button
                    className="bg-red-500 text-white py-1.5 px-3 rounded hover:bg-red-600"
                    onClick={() => handleDelete(node.id)}
                  >删除</button>
                </td>
              </tr>
            ))}
            {nodes.length === 0 && (
              <tr>
                <td colSpan={7} className="px-6 py-4 text-center text-gray-500">暂无数据</td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      {/* 弹窗 */}
      {showModal && (
        <div className="fixed inset-0 flex items-center justify-center z-50">
          <div className="absolute inset-0 bg-black bg-opacity-40" onClick={() => setShowModal(false)}></div>
          <div className="bg-white dark:bg-gray-800 p-6 rounded-xl shadow-lg z-10 w-full max-w-md">
            <h2 className="text-2xl font-semibold mb-4 text-gray-900 dark:text-white">
              {currentNode?.id ? '编辑节点' : '新增节点'}
            </h2>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div>
                <label className="block text-gray-700 dark:text-gray-300 mb-1">节点名称</label>
                <input
                  type="text"
                  value={currentNode?.name || ''}
                  onChange={e => setCurrentNode({...currentNode, name: e.target.value})}
                  required
                  className="w-full px-3 py-2 border rounded-lg border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>
              <div>
                <label className="block text-gray-700 dark:text-gray-300 mb-1">IP地址</label>
                <input
                  type="text"
                  value={currentNode?.host || ''}
                  onChange={e => {
                    setCurrentNode({...currentNode, host: e.target.value})
                  }}
                  required
                  className="w-full px-3 py-2 border rounded-lg border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>
              <div>
                <label className="block text-gray-700 dark:text-gray-300 mb-1">SSH 用户</label>
                <input
                  type="text"
                  value={currentNode?.ssh_user || 'root'}
                  onChange={e => setCurrentNode({...currentNode, ssh_user: e.target.value})}
                  className="w-full px-3 py-2 border rounded-lg border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>
              <div>
                <label className="block text-gray-700 dark:text-gray-300 mb-1">SSH 端口</label>
                <input
                  type="number"
                  value={currentNode?.ssh_port || 22}
                  onChange={e => setCurrentNode({...currentNode, ssh_port: Number(e.target.value)})}
                  className="w-full px-3 py-2 border rounded-lg border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>
              <div className="flex items-center space-x-2">
                <input
                  type="checkbox"
                  checked={currentNode?.status ?? true}
                  onChange={e => setCurrentNode({...currentNode, status: e.target.checked})}
                  className="w-4 h-4"
                />
                <span className="text-gray-700 dark:text-gray-300">启用节点</span>
              </div>
              <div className="flex justify-end space-x-3 pt-2">
                <button type="button" className="bg-gray-400 text-white py-2 px-4 rounded hover:bg-gray-500" onClick={() => setShowModal(false)}>取消</button>
                <button type="submit" className="bg-blue-600 text-white py-2 px-4 rounded hover:bg-blue-700">保存</button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

export default CdnNodePage;
